import reactLogo from './assets/react.svg'
import './App.css'
import {Button, Card, Form, Input} from "antd";
import axios from "axios";
axios.defaults.withCredentials = true
import {useEffect, useState} from "react";

function App() {
    const request = axios.create({
            baseURL: "http://localhost:9772/user",
            timeout: 5000
        }
    )

    const [userInfo, setUserInfo] = useState("用户未登录");
    const [isLogin, setIsLogin] = useState(false)

    const login = async (values) => {
        const res = await request({url: "/login", method: "GET", params:values})
        console.log("请求返回的数据为", res)
        if (res != null) {
            setIsLogin(true)
            setUserInfo(res.data)
        }

    }

    const getUserInfo = async ()=>{
        const res = await request({url:"/getUserInfo",method:"GET"})
        console.log(res)
        if(res.data!='当前没有登陆，请跳转'){
            console.log("登陆了，将用户信息展示到前端")
            setIsLogin(true)
            setUserInfo(res.data)
        }
    }

    const logout = async ()=>{
        await request({url:"/logout",method:"GET"})
    }

    useEffect(()=>{
        getUserInfo()
    })

    return (
        <div>
            {isLogin &&
                <div>
                    <h4>{userInfo}</h4>
                    <Button type="primary" onClick={logout}>注销</Button>
                </div>

            }
            {!isLogin && <Card>
                <img className="login-logo" src={reactLogo} alt="" style={{marginBottom: "20px"}}/>
                <Form validateTrigger='onBlur' onFinish={login}>
                    <Form.Item
                        name="userId"
                        rules={[
                            {
                                required: true,
                                message: '请输入账户名'
                            }
                        ]}
                    >
                        <Input size="large" placeholder="请输入账户名"/>
                    </Form.Item>
                    <Form.Item
                        name="userPassword"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码',
                            }
                        ]}
                        style={{marginBottom: "5px"}}
                    >
                        <Input.Password size="large" placeholder="密码"/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" size="large" block>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </Card>}
        </div>
    )
}

export default App
